<?php

class Result
{

    public static function get ()
    {
        $r = json_decode(self::random());
        
        $rtn['time'] = date("Y-m-d H:i:s");
        $rtn['s1'] = $r->s1;
        $rtn['s2'] = $r->s2;
        $rtn['s3'] = $r->s3;
        $rtn['check'] = $r->check;
        $rtn['result'] = $r->msg;
        // save result
        $id = $rtn['s1'];
        $names = json_decode(self::getPrizeName(), true);
        $name = isset($names["names"][$id]) ? $names["names"][$id] : '';
        if ($r->msg == 'win')
            self::save($rtn['time'] . ", $id: $name, " . $rtn['check'] . "\n");
        
        return json_encode($rtn);
    }

    public static function random ()
    {
        $s1 = 0;
        $s2 = 0;
        $s3 = 0;
        $win_poss = json_decode(self::getWinPoss());
        $prob_winer = (int)($win_poss->winposs);
        $prob_loser = 100-$prob_winer;
        $prize_result = self::weighted_random(
                array(
                        'win',
                        'lose'
                ), 
                array(
                        $prob_winer,
                        $prob_loser
                ));
        $alltotal = 0;
        $allprize = json_decode(self::getPrize());
        $all_id = array();
        $all_amount = array();
        foreach ($allprize as $k => $v) {
            if ($v->amount == 0)
                continue;
            $alltotal += $v->amount;
            array_push($all_id, $k);
            array_push($all_amount, $v->amount);
        }
        if ($prize_result == 'win' && $alltotal > 0) {
            $present = self::weighted_random($all_id, $all_amount);
            $s1 = $present;
            $s2 = $present;
            $s3 = $present;
            $rtn['msg'] = 'win';
            // if not the right time, the winer will be canceled;
            if (date("H") <= 12 && $present == '1')
                $prize_result = 'lose';
            else
                self::savePrize($present, ($allprize->$present->amount - 1));
        }
        if ($prize_result == 'lose' || $alltotal <= 0) {
            do {
                $s1 = rand(1, 50);
                $s2 = rand(1, 50);
                $s3 = rand(1, 50);
            } while (($s1 == $s2) && ($s2 == $s3));
            $rtn['msg'] = ($alltotal <= 0) ? 'empty' : 'lose';
        }
        $rtn['s1'] = $s1;
        $rtn['s2'] = $s2;
        $rtn['s3'] = $s3;
        $rtn['check'] = date("His") . rand(10, 99);
        return json_encode($rtn);
    }

    private static function weighted_random ($values, $weights)
    {
        $count = count($values);
        $i = 0;
        $n = 0;
        $num = mt_rand(0, array_sum($weights));
        while ($i < $count) {
            $n += $weights[$i];
            if ($n >= $num) {
                break;
            }
            $i ++;
        }
        return $values[$i];
    }

    private static function save ($data)
    {
        $file = __DIR__ . '/../result/' . date('Ymd') . '.csv';
        if (! is_dir("result")) {
            // dir doesn't exist, make it
            mkdir("result");
        }
        if (file_exists($file)) {
            $allresult = file_get_contents($file);
            file_put_contents($file, $allresult . $data);
        } else {
            $data = "時間, 獎項, 檢核碼\n" . $data;
            file_put_contents($file, $data);
        }
    }

    public static function getWinPoss ()
    {
        $file = 'tmp/possibillity';
        if (file_exists($file)) {
            $poss = unserialize(file_get_contents($file));
        } else {
            // default
            $poss = array();
            file_put_contents($file, serialize($poss));
        }
        return json_encode($poss);
    }
    
    public static function saveWinPoss ($data)
    {
        $file = 'tmp/possibillity';
        if (! is_dir("tmp")) {
            // dir doesn't exist, make it
            mkdir("tmp");
        }
        file_put_contents($file, serialize($data));
    }
    
    public static function getPrize ()
    {
        $file = 'tmp/prize-' . date('Ymd');
        if (file_exists($file)) {
            $prize = unserialize(file_get_contents($file));
        } else {
            if (! is_dir("tmp")) {
                mkdir("tmp");
            }
            // default
            $prize = array();
            file_put_contents($file, serialize($prize));
        }
        return json_encode($prize);
    }

    public static function savePrize ($id, $amount)
    {
        $file = 'tmp/prize-' . date('Ymd');
        if (file_exists($file)) {
            $prize = unserialize(file_get_contents($file));
        } else {
            // default
            $prize = array();
        }
        $prize[$id] = array(
                'amount' => $amount
        );
        file_put_contents($file, serialize($prize));
        $rtn['success'] = true;
        $rtn['data'] = $prize;
        return json_encode($rtn);
    }

    public static function savePrizeName ($data)
    {
        $file = 'tmp/prize-name';
        
        if (! is_dir("tmp")) {
            mkdir("tmp");
        }
        file_put_contents($file, serialize($data));
    }

    public static function getPrizeName ()
    {
        $file = 'tmp/prize-name';
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
        } else {
            $data = array();
        }
        return json_encode($data);
    }
}
